package com.douwong.student.fragment;

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;
import android.widget.Toast;

import com.douwong.student.R;
import com.douwong.student.activity.PrepareActivity;
import com.douwong.student.adapter.PrepareAdapter;
import com.douwong.student.application.BaseApplication;
import com.douwong.student.contant.CommonConfig;
import com.douwong.student.contant.Config;
import com.douwong.student.interfaces.WorkResultNotify;
import com.douwong.student.model.Prepare;
import com.douwong.student.model.RequestAction;
import com.douwong.student.task.PrepareListTask;
import com.douwong.student.utils.ToastUtils;
import com.douwong.student.view.PullToRefreshListView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


/**
 * 备课预习碎片
 * 
 * @author Administrator
 *
 */
@SuppressLint("ValidFragment")
public class PrepareFragment extends Fragment {

	private PrepareAdapter adapter;
	private View view;
	private TextView scan_line_text;
	private PullToRefreshListView prepare_listview;
	private PrepareActivity activity;
	private ArrayList<Prepare> list;
	private BaseApplication app;
	private String startTime=null;
	private String endTime=null;
	private String subjectId=null;
	private boolean isRefreshing = false;
	private int visibleLastIndex = 0, currentPageIndex = 1;
	

	public PrepareFragment() {
	}

	public PrepareFragment(PrepareActivity activity) {
		this.activity = activity;
		app = (BaseApplication) activity.getApplication();
	}

	IntentFilter filter = new IntentFilter() {
		{
			addAction(Config.PREPARE_SEARCH);
			
		}
	};
	BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			if(intent.getAction().equals(Config.PREPARE_SEARCH)){
				startTime=intent.getStringExtra("start_time");
				endTime=intent.getStringExtra("end_time");
				subjectId=intent.getStringExtra("subjectId");
				updateData(RequestAction.REFRESH, 1,true);
			}
		}

	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.prepare_layout, null);
		scan_line_text = (TextView) view.findViewById(R.id.scan_line_text);
		// scan_line_text.setVisibility(View.GONE);
		prepare_listview = (PullToRefreshListView) view.findViewById(R.id.prepare_listview);
		prepare_listview.setOverScrollMode(View.OVER_SCROLL_NEVER);
		list = new ArrayList<Prepare>();
		adapter = new PrepareAdapter(getActivity(), list);
		prepare_listview.setAdapter(adapter);
		getActivity().registerReceiver(receiver, filter);
		updateData(RequestAction.INIT, 1,false);
		prepare_listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				activity.showFragment(activity.mNavData.get(4));
				activity.selectItem = 4;
				activity.hasChild = true;
				Intent intent = new Intent();
				intent.setAction(CommonConfig.PREPARE_DETAIL);
				intent.putExtra("prepareId", list.get(position - 1).getId());
				getActivity().sendBroadcast(intent);

			}
		});
		/*prepare_listview.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				prepare_listview.onScrollStateChanged(view, scrollState);
				if (isRefreshing) {
					return;
				}

				int lastItemIndex = adapter.getCount();
				if (scrollState == OnScrollListener.SCROLL_STATE_IDLE && visibleLastIndex == lastItemIndex) {

					if (30 * (currentPageIndex) <= adapter.getCount()) {
						++currentPageIndex;
						updateData(RequestAction.LOADMROE, currentPageIndex,false);
						isRefreshing = true;
					}
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
				prepare_listview.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
//				Log.e("开始刷新", "开始刷新");
				visibleLastIndex = firstVisibleItem + visibleItemCount - 1;
			}
		});*/
		prepare_listview.setOnILoadMoreListener(new PullToRefreshListView.OnILoadMoreListener() {
			@Override
			public void onLoadMore() {
				if (isRefreshing) {
					return;
				}
				++currentPageIndex;
				updateData(RequestAction.LOADMROE, currentPageIndex,false);
				isRefreshing = true;
			}
		});
		prepare_listview.setOnRefreshListener(new PullToRefreshListView.OnRefreshListener() {

			@Override
			public void onRefresh() {
				updateData(RequestAction.REFRESH, 1,false);
			}


		});
		return view;
	}

	protected void updateData(final RequestAction action, int pageIndex,boolean isSearch) {

		PrepareListTask task = new PrepareListTask(isSearch,action, app);
		task.setWorkStautsListener(new WorkResultNotify<Prepare>() {

			@Override
			public void notify(int stateCode, List<Prepare> arryResult) {
				if (PrepareListTask.NO_DATA == stateCode) {

					// 加载更多时，出现异常或者没有多余数据，要将currentPageIndex回到加载数据前的一页
					if (currentPageIndex > 1 && RequestAction.LOADMROE == action) {
						--currentPageIndex;
					}
					if (arryResult == null) {
						//list.clear();
						ToastUtils.makeText(activity,"没有更多数据了");
					}

					
				} else if (PrepareListTask.REQUESTOK == stateCode) {
					// 其他访问类型均需要清空当前数据，重新显示，加载更多是在原有的数据上增加
					if (RequestAction.LOADMROE != action) {
						list.clear();
					}
					if (arryResult != null) {
						list.addAll(arryResult);
						Collections.sort(list);
					}
				}
				isRefreshing = false;
				prepare_listview.onRefreshComplete();
				prepare_listview.completeLoadMore();
				adapter.notifyDataSetChanged();
			}
		});
		if (BaseApplication.sUserBean == null) {
			isRefreshing = false;
			prepare_listview.onRefreshComplete();
			Toast.makeText(getActivity(), R.string.login_please, Toast.LENGTH_LONG).show();
		} else {
			if(RequestAction.REFRESH==action&&!isSearch){
//				startTime=null;
//				endTime=null;
			}
			task.execute(String.valueOf(pageIndex),subjectId,startTime,endTime);
		}
	}
	@Override
	public void onDestroyView() {
		super.onDestroyView();
		getActivity().unregisterReceiver(receiver);
	}
}
